import { useRequest } from 'ahooks';
import { Button, Form, Input } from 'antd';
import { observer } from 'mobx-react-lite';

import { useStore } from '@/store';

import { passwordValidator } from '@/config/rule';
import { securityPublicKey } from '@/services/base/denglumokuaidenglujiekou';
import { orgUserInfoSelfPassword } from '@/services/base/yonghuguanliyonghumimaxiangguanjiekou';
import { encryptRSA } from '@/utils/encrypt';

type FormValues = {
  checkPassword: string;
  password: string;
  rePassword: string;
};

const Page: React.FC = () => {
  const [form] = Form.useForm<FormValues>();
  const store = useStore();
  const submit = useRequest(
    async (values: FormValues) => {
      // 加密密码
      const publicKey = (await securityPublicKey()).data;
      const checkPassword = await encryptRSA(values.checkPassword, async () => publicKey);
      const password = await encryptRSA(values.password, async () => publicKey);

      await orgUserInfoSelfPassword({
        password,
        checkPassword
      } as ArgumentsType<typeof orgUserInfoSelfPassword>[0]);

      store.app?.message.success('修改密码成功，请重新登录');

      store.logout();
    },
    {
      manual: true
    }
  );

  return (
    <>
      <Form<FormValues>
        form={form}
        layout="horizontal"
        labelWrap
        labelCol={{ span: 3 }}
        wrapperCol={{ span: 8 }}
        onFinish={submit.run}
        disabled={submit.loading}
      >
        <Form.Item
          name="checkPassword"
          label="原密码"
          rules={[{ required: true, message: '请输入原密码' }]}
        >
          <Input.Password allowClear />
        </Form.Item>

        <Form.Item
          label="新密码"
          name="password"
          rules={[
            { required: true, message: '请输入新密码' },
            {
              validator: passwordValidator
            }
          ]}
          hasFeedback
        >
          <Input.Password placeholder="请输入新密码" allowClear autoComplete="new-password" />
        </Form.Item>

        <Form.Item
          label="确认密码"
          name="rePassword"
          dependencies={['password']}
          hasFeedback
          rules={
            [
              { required: true, message: '请确认新密码' },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue('password') === value) {
                    return Promise.resolve();
                  }

                  return Promise.reject(new Error('两次输入的密码不一致!'));
                }
              })
            ]!
          }
        >
          <Input.Password placeholder="请确认新密码" allowClear autoComplete="new-password" />
        </Form.Item>

        <Form.Item wrapperCol={{ offset: 3, span: 8 }}>
          <Button
            loading={submit.loading}
            disabled={submit.loading}
            size="large"
            type="primary"
            htmlType="submit"
            block
          >
            保存
          </Button>
        </Form.Item>
      </Form>
    </>
  );
};

export default observer(Page);
